#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <assert.h>

void usage(const char *this_prog)
{
	fprintf(stderr, "Usage: %s <intsequencefile> [<intsequencefile>...]\n", this_prog);
	fprintf(stderr, "Input file(s) should contain 32-bit integers\n");
	exit(1);
}

int main(int argc, char *argv[])
{
	int32_t x;
	int i, n_files = 0;
	FILE *infiles[argc == 1 ? 1 : argc - 1];
	int done = 0;

	if(argc == 1) {
		usage(argv[0]);
	}

	for(i=1; i<argc; i++) {
		FILE *nextfile = fopen(argv[i], "r");
		if(nextfile == NULL) {
			perror(argv[i]);
			exit(1);
		}
		infiles[n_files++] = nextfile;
	}

	char linebuf[10 * (n_files + 1) + 1]; // 10 chars per column, 1 col/file + 1 col for line number, 1 for zero terminator
	int lineno = 0;
	while(!done) {
		done = 1;
		char *linepos = linebuf;

		linepos += sprintf(linepos, "%10d", lineno++);
		for(i=0; i<n_files; i++) {
			int nr = 0;
			if(infiles[i]) {
				nr = fread(&x, sizeof(int32_t), 1, infiles[i]);
				if(nr == 0) {
					// let the OS close
					infiles[i] = NULL;
				}
			}

			if(nr) {
				linepos += sprintf(linepos, "%10d", x);
				done = 0;
			}
			else {
				char *nada = "";
				linepos += sprintf(linepos, "%10s", nada);
			}
		}
		if(!done) {
			puts(linebuf);
		}

		assert(linepos <= (linebuf + sizeof(linebuf)));
	}

	return 0;
}
